//
//  AppDelegate+ThridParty.swift
//  CHT
//
//  Created by aiquantong on 2019/2/21.
//  Copyright © 2019 difan. All rights reserved.
//

import UIKit
import AdSupport
import Bugly
import IQKeyboardManagerSwift

extension AppDelegate : WXApiDelegate {
    
    public func initThirdParty(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Void {
        initBugly()
        initLog()
        initIQKeyboardManager()
        initSDK(launchOptions)
        #if TARGET_OS_IPHONE
        initJPush(launchOptions)
        #endif
    }
    
    func initBugly() -> Void {
        let bc = BuglyConfig()
        if(AppConfig.IS_DEBUG_MODE){
            bc.channel = "debug"
        }else{
            bc.channel = "release"
        }
        Bugly.start(withAppId: AppConfig.Bugly_App_Id, config: bc)
    }
    
    func initLog() -> Void {
        LogManager.share().isDebug = AppConfig.IS_DEBUG_MODE;
    }
    
    func initSDK(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Void {
        
        //TODO: WX
        if(AppConfig.IS_DEBUG_MODE){
            WXApi.startLog(by: WXLogLevel.detail,
                           logBlock: {(_log) in log.debug("WXApi log \(_log)")}
            );
        }
        let rt = WXApi.registerApp(AppConfig.WX_APP_ID)
        log.info("initSDK WXApi : \(WXApi.getVersion()) registerApp: \(rt)")
        
        //TODO: alipay
        
    }
    
    
    func initIQKeyboardManager() -> Void {
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 5.0
        IQKeyboardManager.shared.shouldResignOnTouchOutside = false
        IQKeyboardManager.shared.toolbarManageBehaviour = IQAutoToolbarManageBehaviour.byPosition
    }
    
    // MARK: PUSH
    func initJPush(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Void {
        //JPush
        JPUSHService.setup(withOption: launchOptions,
                           appKey: AppConfig.JMESSAGE_APPKEY,
                           channel: AppConfig.CHANNEL,
                           apsForProduction: AppConfig.APSFORPRO)
        
        UIApplication.shared.applicationIconBadgeNumber = 0
        let types = UIUserNotificationType.badge.rawValue|UIUserNotificationType.sound.rawValue|UIUserNotificationType.alert.rawValue
        JPUSHService.register(forRemoteNotificationTypes:types, categories: nil);
        
    }
    
    func  application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        UIApplication.shared.registerForRemoteNotifications();
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        log.info("didFailToRegisterForRemoteNotificationsWithError error \(error)")
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        log.info("didRegisterForRemoteNotificationsWithDeviceToken deviceToken \(deviceToken)")
        
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func  application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo);
        handleReceiveRemoteNotification(userInfo);
    }
    
    public func handleReceiveRemoteNotification(_ userInfo: [AnyHashable : Any]) -> Void {
        self.remoteNotification = userInfo;
        
    }
    
    // MARK: wechat and alipay
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    
        return true;
    }
    
    func onResp(_ resp: BaseResp) {
        if resp is PayResp {
            let response : PayResp = resp as! PayResp;
            if response.errCode == WXSuccess.rawValue {
                payOk()
            }else{
                payFail()
            }
        }else if resp is SendMessageToWXResp {
            
        }
    }

    public func payOk() -> Void {
        let povc = PayOkViewController.init(nibName: "PayOkViewController", bundle: nil);
        
    }
    
    public func payFail() -> Void {
        let fovc = PayFailViewController.init(nibName: "PayFailViewController", bundle: nil);
        
    }
    
    // MARK: Keyboard
    func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool {
        return true;
    }
    
    
}

